package com.bodacn.keypoint;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bodacn.keypoint.adapter.ClothPieceGrAdapter;
import com.bodacn.keypoint.adapter.ClothPieceLvAdapter;
import com.bodacn.keypoint.adapter.ClothSizeLvHisAdapter;
import com.bodacn.keypoint.bean.ClothPieceBean;
import com.bodacn.keypoint.bean.ClothPieceCheckBean;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ClothPieceCheckActivity extends AppCompatActivity {

    @BindView(R.id.gr)
    GridView gr;

    @BindView(R.id.btn_cancle)
    Button btnCancle;
    @BindView(R.id.btn_commit)
    Button btnCommit;
    @BindView(R.id.tv_code)
    TextView tvCode;
    @BindView(R.id.tv_color)
    TextView tvColor;
    @BindView(R.id.tv_size)
    TextView tvSize;
    @BindView(R.id.tv_sell)
    TextView tvSell;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.tv_style)
    TextView tvStyle;
    @BindView(R.id.iv_style)
    ImageView ivStyle;
    @BindView(R.id.btn_editBarcode)
    ImageButton btneditBarcode;

    //拦截扫描枪输入部分
    String BarcodeStr = "";
    ScannerManager scannerManager;
    @BindView(R.id.lv)
    ListView lv;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.edt_barcode)
    EditText edtBarcode;
    @BindView(R.id.btn_find)
    Button btnFind;
    @BindView(R.id.iv_add)
    TextView ivAdd;
    @BindView(R.id.tv_PartName)
    TextView tvPartName;
    @BindView(R.id.tv_NormalSize)
    TextView tvNormalSize;
    @BindView(R.id.tv_ScaleAdd)
    TextView tvScaleAdd;
    @BindView(R.id.tv_grid_planNum)
    TextView tvGridPlanNum;
    @BindView(R.id.tv_grid_arrangeNum)
    TextView tvGridArrangeNum;
    @BindView(R.id.tv_grid_targetNum)
    TextView tvGridTargetNum;
    @BindView(R.id.mylistitem)
    LinearLayout mylistitem;
    @BindView(R.id.lv_histoty)
    ListView lvHistoty;
    private String TAG = getClass().getSimpleName();
    private final int MSG_SCAN = 1002;
    private final int MSG_DETAIL = 1003;
    public static final int msgShowImage = 1005;
    public static final int MSG_HISTORY = 1006;
    public static final int msgGetImg = 1007;
    private final int MSG_ERROR=1008;
    public static final int MSG_SelecItem = 1009;
    String curImageFileName = "", curStyleID = "",CurDepartNo="";

    JSONArray scanJson, detailJson, historyJson;
    private List<ClothPieceBean> histotyDatabeans = new ArrayList<>();
    private ClothPieceLvAdapter adapter;
    private ClothPieceGrAdapter grAdapter;
    private ClothSizeLvHisAdapter hisAdapter;
    private List<String> grString = new ArrayList<>();
    private String PO = "", PackList = "", OrderNo = "", StyleNo = "", StyleSort = "", ColorNo = "", CustColor = "", Color = "", Size = "", TermNo = "", UserNo = "";
    public static final int MSG_Submit = 1004;
    private List<ClothPieceCheckBean> commitQeBeans = new ArrayList<>();
    int curIndex=-1;
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (scannerManager.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cloth_piece_check);
        ButterKnife.bind(this);
        initview();
    }

    private void initview() {
        //拦截扫描事件
        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
            @Override
            public void onResult(String code,String deviceName) {
                Log.d(TAG, "code= " + code);
                playRingtone();
                searchBarcodeData(code, "ScanBarcode");
            }
        },this);

        grAdapter = new ClothPieceGrAdapter(grString, this,-1);
        gr.setAdapter(grAdapter);
        gr.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (commitQeBeans!=null&&commitQeBeans.size()>0){
                    adapter = new ClothPieceLvAdapter(commitQeBeans.get(position).getClothSizeBeans(), ClothPieceCheckActivity.this);
                    lv.setAdapter(adapter);
                    curIndex=position;
                }

            }
        });


        gr.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                System.out.println("setOnItemLongClickListener");
                if (commitQeBeans!=null&&commitQeBeans.size()>0){
                    System.out.println("setOnItemLongClickListener-onItemLongClick1");
                    grString.remove(position);
                    grAdapter.notifyDataSetChanged();

                    commitQeBeans.remove(position);
                    //edtBarcode.setText(commitQeBeans.get(position).getBarcode());
                    System.out.println("setOnItemLongClickListener-onItemLongClick2");
                    curIndex=commitQeBeans.size()-1;

                    List<ClothPieceBean>list=new ArrayList<>();
                    if (curIndex>-1){
                        list.clear();
                        list.addAll(commitQeBeans.get(curIndex).getClothSizeBeans());
                        adapter = new ClothPieceLvAdapter(list, ClothPieceCheckActivity.this);
                        lv.setAdapter(adapter);
                    } else{
                        list.clear();
                        adapter = new ClothPieceLvAdapter(list, ClothPieceCheckActivity.this);
                        lv.setAdapter(adapter);
                    }
                    System.out.println("setOnItemLongClickListener-onItemLongClick3");
                    //刷新界面;
                    Message msg = new Message();
                    msg.what = MSG_SelecItem;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                }
                return false;
            }
        });



        hisAdapter = new ClothSizeLvHisAdapter(histotyDatabeans, this);
        lvHistoty.setAdapter(hisAdapter);

        //获取登陆参数
        Bundle paramBundle = this.getIntent().getExtras();
        if (paramBundle != null) {
            UserNo = paramBundle.getString("LoginUserNo", "");
            CurDepartNo = paramBundle.getString("CurDepartNo", "");
        }
    }

    //扫码获取图片 扫码信息
    private void searchBarcodeData(String code, String type) {
        if (grString != null && grString.size() < 5 ) {
        String packlist = "";
        if (!TextUtils.isEmpty(PackList)) {
            if (!PackList.contains(code)) {
                packlist = PackList + "," + code;
            } else {
                packlist = PackList;
            }
        } else {
            packlist = code;
        }
        String SqlComm = "exec  KeyPoint_PieceSize_ScanBarcode  @OperType ='" + type + "',@BarCode='" + code + "'" +
                ",@OrderNo ='" + OrderNo + "',@StyleNo ='" + StyleNo + "',@StyleSort ='" + StyleSort + "',@ColorNo ='"
                + ColorNo + "',@CustColor='" + CustColor + "',@Color ='" + Color + "',@Size ='" + Size + "',@TermNo ='"
                + TermNo + "',@UserNo ='" + UserNo + "',@PackList ='" + packlist + "'";
        ReadSQLData(SqlComm);
        edtBarcode.setText("");
        } else {
            Toast.makeText(ClothPieceCheckActivity.this, "最多添加5条", Toast.LENGTH_LONG).show();
        }
    }

    //直接连获取数据，与Handler配套使用;
    private void ReadSQLData(final String SQLComm) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("过程" + SQLComm);
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(SQLComm);
                    System.out.println("结果" + jsonArray);
                    //往界面转数据;
                    if ((jsonArray != null) && (jsonArray.length() > 0)) {
                        String OPERTYPE = "";
                        if (jsonArray.optJSONObject(0).has("OPERTYPE") == true)
                            OPERTYPE = jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (jsonArray.optJSONObject(0).has("OperType") == true)
                            OPERTYPE = jsonArray.optJSONObject(0).getString("OperType");
                        //获取扫码内容
                        if (OPERTYPE.equals("ScanBarcode")) {
                            scanJson = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_SCAN;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        //获取详情
                        if (OPERTYPE.equals("GetDetail")) {
                            detailJson = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_DETAIL;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        //获取历史
                        if (OPERTYPE.equals("GetHistory")) {
                            historyJson = jsonArray;
                            //刷新界面;
                            Message msg = new Message();
                            msg.what = MSG_HISTORY;
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        };
        new Thread(run).start();

    }

    private void getImage(final String paramStyleID, final String paramStyleNo, final String paramStyleSort) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    ResultSet re = DBUtil.OpenSQL("Exec KeyPoint_GetStylePNG @StyleID='" + paramStyleID + "',@StyleNo='" + paramStyleNo + "',@StyleSort='" + paramStyleSort + "'");
                    if (re != null) {
                        re.next();
                        //使用Blob对象接收数据库里的图片
                        if (re.findColumn("ImgResult") > -1) {
                            String ImgResult = re.getString("ImgResult");
                            if (ImgResult.equals("OK")) {
                                Blob imgBlob = re.getBlob("ImgFile");
                                //获取Blob对象的二进制流;
                                InputStream imgInS = imgBlob.getBinaryStream();
                                //加载一个网络图片
                                Bitmap bitmap = BitmapFactory.decodeStream(imgInS);
                                //保存图片;
                                saveBitmap(bitmap, curImageFileName);
                                //发消息显示图片;
                                Message msg = new Message();
                                msg.what = msgShowImage;
                                handler.removeMessages(msg.what);
                                handler.sendMessage(msg);
                            }
                        }
                    }
                    re.getStatement().getConnection().close();
                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        new Thread(run).start();
    }


    //设置焦点到扫描输入框
    private void setEditBarcodeFocus()
    {

        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        if (edtBarcode!=null) {
            edtBarcode.selectAll();
            edtBarcode.setFocusable(true);
            edtBarcode.setFocusableInTouchMode(true);
            edtBarcode.requestFocus();
            edtBarcode.requestFocusFromTouch();
            hideIM(edtBarcode);
            hideBottomUIMenu();
        }
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }
    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏状态栏和底部虚拟按键
        View decorView = this.getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flag = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
            decorView.setSystemUiVisibility(flag);
        }
    }


    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            setEditBarcodeFocus();
            int msgId = msg.what;
            switch (msgId) {
                case MSG_ERROR:
                    if (msg.getData().getString("HintInfo") != null) {
                        //提示信息
                        Toast.makeText(ClothPieceCheckActivity.this, msg.getData().getString("HintInfo"), Toast.LENGTH_LONG).show();
                    }
                    break;
                case msgShowImage:
                    //判断本地是否有图片;
                    String img_file_path = getCacheDir().toString();
                    File file = new File(img_file_path + "/" + curImageFileName);
                    //判断图片是否存在，如果不存在则从网络获取;
                    if (file.exists() == true) {
                        Log.d(TAG, "准备从本地取图片显示---------------");
                        //从本地取图片
                        Bitmap bitmap = getLoacalBitmap(img_file_path + "/" + curImageFileName);
                        ivStyle.setImageBitmap(bitmap);
                    }
                    break;
                case msgGetImg:
                    //设置焦点
                    System.out.println(TAG + "获取图片-------------------------------1.Start");
                    if (curImageFileName.length() > 0)
                        getImage(curStyleID, tvOrder.getText().toString(), tvStyle.getText().toString());
                    System.out.println(TAG + "获取图片-------------------------------1.End");
                    break;
                //扫码获取图片信息等
                case MSG_SCAN:
                    try {
                        if (scanJson != null && scanJson.length() > 0) {
                            //扫码信息
                            if (scanJson.getJSONObject(0).has("Barcode")) {
                                edtBarcode.setText(scanJson.getJSONObject(0).getString("Barcode"));
                            }
                            if (scanJson.getJSONObject(0).has("StyleID") == true) {
                                curStyleID = scanJson.getJSONObject(0).getString("StyleID");
                            }
                            //货号
                            if (scanJson.getJSONObject(0).has("StyleNo")) {
                                tvSell.setText(scanJson.getJSONObject(0).getString("StyleNo"));
                                StyleNo = scanJson.getJSONObject(0).getString("StyleNo");
                            }
                            //合约号
                            if (scanJson.getJSONObject(0).has("OrderNo")) {
                                tvOrder.setText(scanJson.getJSONObject(0).getString("OrderNo"));
                                OrderNo = scanJson.getJSONObject(0).getString("OrderNo");
                            }
                            //颜色
                            if (scanJson.getJSONObject(0).has("Color")) {
                                tvColor.setText(scanJson.getJSONObject(0).getString("Color"));
                                Color = scanJson.getJSONObject(0).getString("Color");
                            }
                            //尺码
                            if (scanJson.getJSONObject(0).has("Size")) {
                                tvSize.setText(scanJson.getJSONObject(0).getString("Size"));
                                Size = scanJson.getJSONObject(0).getString("Size");
                            }
                            //款式
                            if (scanJson.getJSONObject(0).has("StyleSort")) {
                                tvStyle.setText(scanJson.getJSONObject(0).getString("StyleSort"));
                                StyleSort = scanJson.getJSONObject(0).getString("StyleSort");
                            }
                            //款式
                            if (scanJson.getJSONObject(0).has("Size")) {
                                tvSize.setText(scanJson.getJSONObject(0).getString("Size"));
                                Size = scanJson.getJSONObject(0).getString("Size");
                            }
                            //PO
                            if (scanJson.getJSONObject(0).has("PO")) {
                                tvCode.setText(scanJson.getJSONObject(0).getString("PO"));
                                PO = scanJson.getJSONObject(0).getString("PO");
                            }
                            //packlist
                            if (scanJson.getJSONObject(0).has("PackList")) {
                                PackList = scanJson.getJSONObject(0).getString("PackList");
                            }
                            if (scanJson.getJSONObject(0).has("LoadDetail")) {
                                //要刷新尺寸信息
                                if (scanJson.getJSONObject(0).getString("LoadDetail").equals("Y")) {
                                    searchBarcodeData(edtBarcode.getText().toString(), "GetDetail");
                                }
                            }
                            if (scanJson.getJSONObject(0).has("ImgFileName")) {
                                curImageFileName = scanJson.getJSONObject(0).getString("ImgFileName");
                                //判断本地是否有图片;
                                String imgfilepath1 = ClothPieceCheckActivity.this.getCacheDir().toString();
                                Log.e(TAG, "imgfilepath1" + imgfilepath1);
                                File file1 = new File(imgfilepath1 + "/" + curImageFileName);
                                System.out.println("图片文件路径:" + imgfilepath1 + "/" + curImageFileName);
                                //判断图片是否存在，如果不存在则从网络获取;
                                if (file1.exists() == true) {
                                    Log.d(TAG, "准备从本地取图片显示---------------");
                                    //从本地取图片
                                    Bitmap bitmap = getLoacalBitmap(imgfilepath1 + "/" + curImageFileName);
                                    ivStyle.setImageBitmap(bitmap);
                                } else {
                                    Log.d(TAG, "发消息从网络获取图片---------------");
                                    Drawable drawable = getResources().getDrawable(R.mipmap.err404);
                                    BitmapDrawable errBitDraw = (BitmapDrawable) drawable;
                                    ivStyle.setImageBitmap(errBitDraw.getBitmap());
                                    //发前消息，获取图片;
                                    Message msg1 = new Message();
                                    msg1.what = msgGetImg;
                                    handler.removeMessages(msg1.what);
                                    handler.sendMessage(msg1);
                                }
                            }
                            if (scanJson.getJSONObject(0).has("ResultInfo")) {
                                //提示信息
                                Toast.makeText(ClothPieceCheckActivity.this, scanJson.getJSONObject(0).getString("ResultInfo"), Toast.LENGTH_LONG).show();
                            }
                            //错误信息
                            if (scanJson.getJSONObject(0).has("ErrInfo") == true) {
                                AlertDialog alertDialog = new AlertDialog.Builder(ClothPieceCheckActivity.this)
                                        .setTitle("系统提示").setMessage(scanJson.getJSONObject(0).getString("ErrInfo"))
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                return;
                                            }
                                        }).create(); // 创建对话框
                                alertDialog.show(); // 显示对话框
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                //获取详情
                case MSG_DETAIL:
                    if (detailJson != null && detailJson.length() > 0) {
                        List<ClothPieceBean> clothPieceBeans = new Gson().fromJson(String.valueOf(detailJson), new TypeToken<List<ClothPieceBean>>() {
                        }.getType());
                        ClothPieceCheckBean firstQEBean = new ClothPieceCheckBean(edtBarcode.getText().toString(), clothPieceBeans);
                        commitQeBeans.add(firstQEBean);
                        adapter = new ClothPieceLvAdapter(commitQeBeans.get(commitQeBeans.size()-1).getClothSizeBeans(), ClothPieceCheckActivity.this);
                        lv.setAdapter(adapter);
                        curIndex=commitQeBeans.size()-1;
                        //加一件成衣;
                        grString.add("衣片");
                        grAdapter.notifyDataSetChanged();
                        grAdapter.setSelectIndex(curIndex);
                        grAdapter.notifyDataSetChanged();
                        //刷新界面;
                        Message msg1 = new Message();
                        msg1.what = MSG_SelecItem;
                        handler.removeMessages(msg1.what);
                        handler.sendMessage(msg1);
                    }
                    //获取历史记录
                    searchBarcodeData(edtBarcode.getText().toString(), "GetHistory");
                    break;
                //获取历史
                case MSG_HISTORY:
                    if (historyJson != null && historyJson.length() > 0) {
                        List<ClothPieceBean> clothPieceBeans = new Gson().fromJson(String.valueOf(historyJson), new TypeToken<List<ClothPieceBean>>() {
                        }.getType());
                        histotyDatabeans.clear();
                        histotyDatabeans.addAll(clothPieceBeans);
                        hisAdapter.notifyDataSetChanged();
                    }
                    break;
                case MSG_Submit:
                    System.out.println("收到的消息是：" + msg.what);
                    Bundle bundle = msg.getData();
                    if (bundle.getString("HintInfo") != null) {
                        AlertDialog alertDialog = new AlertDialog.Builder(ClothPieceCheckActivity.this)
                                .setCancelable(false)
                                .setTitle("系统提示").setMessage(bundle.getString("HintInfo"))
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        tvColor.setText("");
                                        edtBarcode.setText("");
                                        tvOrder.setText("");
                                        tvSell.setText("");
                                        tvSize.setText("");
                                        tvStyle.setText("");
                                        tvCode.setText("");

                                        PO = "";
                                        PackList = "";
                                        OrderNo = "";
                                        StyleNo = "";
                                        StyleSort = "";
                                        ColorNo = "";
                                        CustColor = "";
                                        Color = "";
                                        Size = "";
                                        TermNo = "";
                                        curStyleID = "";
                                        curImageFileName = "";
                                        ivStyle.setImageResource(0);
                                        curIndex=-1;
                                        grString.clear();
                                        grAdapter.notifyDataSetChanged();
                                        commitQeBeans.clear();

                                        lv.setAdapter(null);
                                        return;
                                    }
                                }).create(); // 创建对话框
                        alertDialog.show(); // 显示对话框
                        return;
                    }
                    return;
                case MSG_SelecItem:
                    try {
                        Thread.sleep(100);
                        System.out.println("MSG_SelecItem:"+MSG_SelecItem);
                        if (curIndex<grString.size()&&curIndex>-1)
                            gr.performItemClick(gr.getChildAt(curIndex), curIndex, gr.getItemIdAtPosition(curIndex));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }
    };

    public Bitmap getLoacalBitmap(String url) {
        if (url != null) {
            FileInputStream fis = null;
            try {
                fis = new FileInputStream(url);
                return BitmapFactory.decodeStream(fis); // /把流转化为Bitmap图片
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return null;
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    fis = null;
                }
            }
        } else {
            return null;
        }
    }


    /**
     * 保存文件
     */
    public void saveBitmap(Bitmap bm, String fileName) {
        //获取MainActivity
        //String imgfilepath=activity.SaveFilePath+activity.SaveIMGFolder;
        String imgfilepath = getCacheDir().toString();
        Log.d("saveBitmap", "imgfilepath:" + imgfilepath);
        File f = new File(imgfilepath, fileName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            if (fileName.toUpperCase().indexOf("PNG") > 0)
                bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            if ((fileName.toUpperCase().indexOf("JPG") > 0) || (fileName.toUpperCase().indexOf("JPEG") > 0))
                bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
            Log.i("saveBitmap", "已经保存成功");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    //插放音乐;
    private void playRingtone() {
        Uri notification = Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.scan);
        Ringtone r = RingtoneManager.getRingtone(this, notification);
        r.play();

    }

    @OnClick({R.id.tv_search,R.id.btn_editBarcode, R.id.iv_back, R.id.btn_find, R.id.btn_cancle, R.id.btn_commit, R.id.iv_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_editBarcode:
                edtBarcode.setInputType(InputType.TYPE_CLASS_TEXT);
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) this.getSystemService(this.INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edtBarcode,InputMethodManager.SHOW_FORCED);
                break;
            case R.id.iv_back:
                finish();
                break;
            //衣片复核查询
            case R.id.tv_search:
                Intent outIntent1=new Intent(this,ClothPieceSearchActivity.class);
                Bundle paramBundle=new Bundle();
                paramBundle.clear();
                paramBundle.putString("LoginUserNo", UserNo);
                paramBundle.putString("CurDepartNo", CurDepartNo);
                outIntent1.putExtras(paramBundle);
                startActivity(outIntent1);
                break;
            case R.id.iv_add:
                if (grString != null && grString.size() < 5&&detailJson!=null&&commitQeBeans!=null) {
                    if (!TextUtils.isEmpty(tvColor.getText().toString())) {
                        List<ClothPieceBean> clothPieceBeans = new Gson().fromJson(String.valueOf(detailJson), new TypeToken<List<ClothPieceBean>>() {
                        }.getType());
                        ClothPieceCheckBean firstQEBean = new ClothPieceCheckBean(edtBarcode.getText().toString(), clothPieceBeans);
                        commitQeBeans.add(firstQEBean);
                        adapter = new ClothPieceLvAdapter(commitQeBeans.get(commitQeBeans.size()-1).getClothSizeBeans(), ClothPieceCheckActivity.this);
                        lv.setAdapter(adapter);
                        curIndex=commitQeBeans.size()-1;
                        //加一件成衣;
                        grString.add("衣片");
                        grAdapter.notifyDataSetChanged();
                        grAdapter.setSelectIndex(curIndex);
                        grAdapter.notifyDataSetChanged();
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_SelecItem;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                    } else {
                        Toast.makeText(ClothPieceCheckActivity.this, "请先扫描条码", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(ClothPieceCheckActivity.this, "最多添加5条", Toast.LENGTH_LONG).show();
                }

                break;
            //撤销
            case R.id.btn_cancle:
                if (detailJson!=null){
                    List<ClothPieceBean> clothPieceBeans = new Gson().fromJson(String.valueOf(detailJson), new TypeToken<List<ClothPieceBean>>() {
                    }.getType());
                    if (curIndex>-1&&curIndex<commitQeBeans.size()) {
                        commitQeBeans.get(curIndex).setClothSizeBeans(clothPieceBeans);
                        adapter = new ClothPieceLvAdapter(commitQeBeans.get(curIndex).getClothSizeBeans(), this);
                        lv.setAdapter(adapter);
                    }
                }
                break;
            //提交
            case R.id.btn_commit:
                if (!TextUtils.isEmpty(PackList)) {
                    if (commitQeBeans != null && commitQeBeans.size() > 0) {
                        commit();
                    } else {
                        Toast.makeText(ClothPieceCheckActivity.this, "没有衣片信息", Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(ClothPieceCheckActivity.this, "请至少添加一包", Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.btn_find:
                searchBarcodeData(edtBarcode.getText().toString(), "ScanBarcode");
                break;
        }
    }

    private void commit() {
        //线程直接保存不经过WebService;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                //将数据读到JSONArray;
                String CheckClothMaID = UUID.randomUUID().toString();
                try {

                    PreparedStatement pstmt = DBUtil.getSQLConnection().prepareStatement("insert into QE_PieceSizeDe(PieceSizeDeID,PieceSizeMaID," +
                            "IntID,PartName,NormalSizeV,ScaleAddV,BeforeSewV,WeightSizeV,NormalSizeH,ScaleAddH,BeforeSewH,WeightSizeH,CheckResult,Barcode,SerNo) values(newid(),?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
                    for (int i = 0; i < commitQeBeans.size(); i++) {
                        for (int j = 0; j < commitQeBeans.get(i).getClothSizeBeans().size(); j++) {
                            pstmt.setString(1, CheckClothMaID);
                            pstmt.setString(2, commitQeBeans.get(i).getClothSizeBeans().get(j).getIntID() + "");
                            pstmt.setString(3, commitQeBeans.get(i).getClothSizeBeans().get(j).getPartName());
                            pstmt.setString(4, commitQeBeans.get(i).getClothSizeBeans().get(j).getNormalSizeV());
                            pstmt.setString(5, commitQeBeans.get(i).getClothSizeBeans().get(j).getScaleAddV());
                            pstmt.setString(6, commitQeBeans.get(i).getClothSizeBeans().get(j).getBeforeSewV());
                            pstmt.setString(7, commitQeBeans.get(i).getClothSizeBeans().get(j).getWeightSizeV());
                            pstmt.setString(8, commitQeBeans.get(i).getClothSizeBeans().get(j).getNormalSizeH());
                            pstmt.setString(9, commitQeBeans.get(i).getClothSizeBeans().get(j).getScaleAddH());
                            pstmt.setString(10, commitQeBeans.get(i).getClothSizeBeans().get(j).getBeforeSewH());
                            pstmt.setString(11, commitQeBeans.get(i).getClothSizeBeans().get(j).getWeightSizeH());
                            pstmt.setString(12, commitQeBeans.get(i).getClothSizeBeans().get(j).getCheckResult());
                            pstmt.setString(13, commitQeBeans.get(i).getBarcode());
                            pstmt.setString(14, "成衣"+(i+1));
                            pstmt.executeUpdate();
                        }

                    }
                    pstmt.close();

                    pstmt = DBUtil.getSQLConnection().prepareStatement("Exec KeyPoint_PieceSize_SaveTrans" +
                            " @PieceSizeMaID=?,@OrderNo =?,@StyleNo =?," +
                            " @StyleSort=?,@ColorNo =?," +
                            " @CustColor=?,@Color =?," +
                            " @Size=?,@PackList=?," +
                            " @TermNo=?,@UserNo =?,@PO =?");
                    pstmt.setString(1, CheckClothMaID);
                    pstmt.setString(2, OrderNo);
                    pstmt.setString(3, StyleNo);
                    pstmt.setString(4, StyleSort);
                    pstmt.setString(5, ColorNo);
                    pstmt.setString(6, CustColor);
                    pstmt.setString(7, Color);
                    pstmt.setString(8, Size);
                    pstmt.setString(9, PackList);
                    pstmt.setString(10, TermNo);
                    pstmt.setString(11, UserNo);
                    pstmt.setString(12, PO);
                    ResultSet resultSet = pstmt.executeQuery();
                    System.out.println("checkSaveFabric--A" + resultSet.getRow());
                    if (resultSet.next()) {
                        System.out.println("checkSaveFabric--B");
                        if (DBUtil.isExistColumn(resultSet, "ResultInfo")) {
                            System.out.println("checkSaveFabric--C");
                            //关闭ProgressDialog
                            Message msg = new Message();
                            Bundle bundle = new Bundle();
                            bundle.putString("HintInfo", resultSet.getString("ResultInfo"));
                            msg.what = MSG_Submit;
                            msg.setData(bundle);
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                        if (DBUtil.isExistColumn(resultSet, "ErrInfo")) {
                            System.out.println("checkSaveFabric--D");
                            Message msg = new Message();
                            msg.what = MSG_Submit;
                            Bundle bundle = new Bundle();
                            bundle.putString("HintInfo", resultSet.getString(resultSet.findColumn("ErrInfo")));
                            msg.setData(bundle);
                            handler.removeMessages(msg.what);
                            handler.sendMessage(msg);
                        }
                    }
                    return;
                } catch (SQLException ex) {
                    ex.printStackTrace();
                    Message msg = new Message();
                    msg.what = MSG_ERROR;
                    Bundle bundle = new Bundle();
                    bundle.putString("HintInfo", ex.getMessage());
                    msg.setData(bundle);
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                }
            }
        };
        new Thread(run).start();

    }

}
